/*
 * InputMediaSource.cpp
 *
 *  Created on: 2018年6月24日
 *      Author: zhengboyuan
 */

#include "InputMediaSource.h"
#include "MFormatUtil.h"
#include "FfmpegUtil.h"


namespace av
{

InputMediaSource::InputMediaSource()
{
}

InputMediaSource::~InputMediaSource()
{
}

int InputMediaSource::open(const MFormat& fmt)
{
    MFormatUtil::copyTo(&fmt, m_format);

    return 0;
}

bool InputMediaSource::write(MPacket& pkt)
{
    AVPacketPtr packet(new AVPacket(), ffmpeg::PacketDeleter());
    av_init_packet(packet.get());
    av_new_packet(packet.get(), pkt.size);
    memcpy(packet->data, pkt.data, pkt.size);

    packet->stream_index = pkt.type;
    packet->pts = pkt.pts;
    packet->duration = pkt.duration;
    packet->flags = pkt.flags;

    m_pktQueue.push(packet);

    return true;
}

void InputMediaSource::flush()
{
    m_pktQueue.clear();
}


int InputMediaSource::open(const std::string& url, const std::string& params)
{
    return 0;
}

void InputMediaSource::close()
{
    m_format.clear();
    m_pktQueue.clear();
}

bool InputMediaSource::isOpen()
{
    return m_format.isValid();
}

bool InputMediaSource::getFormat(MediaFormat& fmt)
{
    fmt = m_format;
    return true;
}

int InputMediaSource::getDuration()
{
    return m_format.m_duration;
}

int InputMediaSource::play()
{
    return 0;
}

int InputMediaSource::pause()
{
    return 0;
}

void InputMediaSource::stop()
{
    //
}

int InputMediaSource::getState()
{
    return 0;
}

bool InputMediaSource::seekable()
{
    return false;
}

int InputMediaSource::seek(int64_t offset)
{
    return 0;
}

int64_t InputMediaSource::getTime()
{
    return 0;
}

int InputMediaSource::setScale(float scale)
{
    return 0;
}

float InputMediaSource::getScale()
{
    return 1.0f;
}

int InputMediaSource::read(AVPacket& pkt)
{
    AVPacketPtr packet;
    if (!m_pktQueue.pop(packet, 20))
    {
        return AVERROR(EAGAIN);
    }

    av_init_packet(&pkt);
    av_packet_ref(&pkt, packet.get());

    return 0;
}

void InputMediaSource::interrupt()
{
    m_pktQueue.cancelWait();
}

bool InputMediaSource::isLive()
{
    return m_format.m_duration <= 0;
}

bool InputMediaSource::getMetaData(const std::string& key, std::string& value)
{
    return false;
}



} /* namespace av */
